using System.Reflection;
using CMS.Web.Attributes;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;

namespace CMS.Web.Filters;

public class LoginCheckFilter : IAsyncActionFilter{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) {
        if (context.ActionDescriptor is ControllerActionDescriptor actionDescriptor) {
            MethodInfo methodInfo = actionDescriptor.MethodInfo;
            var loginAttribute = methodInfo.GetCustomAttribute<DoNotCheckLoginAttribute>();
            if (loginAttribute == null) {
                //检查
                if (!string.IsNullOrEmpty(context.HttpContext.Session.GetString("user"))) {
                    await next();
                } else {
                    context.HttpContext.Response.Redirect($"/Login/Index?returnUrl=" + context.HttpContext.Request.Path);
                }
            } else {
                await next();
            }
        }
    }
}